package com.corpgovernment.permission.controller;

import com.corpgovernment.api.permission.vo.*;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.handler.ICacheHandler;
import com.corpgovernment.common.utils.BaseUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.permission.entity.MbPermissionDto;
import com.corpgovernment.permission.service.PermissionService;
import com.corpgovernment.permission.service.UserService;
import com.corpgovernment.permission.vo.FindPermissionVO;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 权限rest接口
 *
 * @author wangyujue
 */
@RestController
@RequestMapping("/permission")
@Slf4j
public class PermissionRest {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userSrv;
    @Autowired
    private ICacheHandler iCacheHandler;

    /**
     * 获得用户权限
     * url: /corpApi/organization/permission/getUserPermission
     * localhost:8787/user/permission/getUserPermission?uid=1
     */
    @GetMapping("/getUserPermission")
    public UserPermissionResponse getUserPermission(String uid) {
        // 获取某用户的所有权限。
        return new UserPermissionResponse();
    }

//    /**
//     * 获取全部权限模块
//     * url: /corpApi/organization/permission/getModuleList
//     */
//    @PostMapping("/getModuleList")
//    public JSONResult<List<ModuleInfo>> getAllPermissionList(BaseUserInfo userInfo, @RequestBody GetAllPermissionListRequest request) {
//        List<MbPermissionDto> mbPermissions = permissionService.getAllPermissionList(request.getIsBackground(), userInfo);
//        List<ModuleInfo> moduleInfos = mbPermissions.stream()
//                .map(x -> new ModuleInfo(x.getResKey(), x.getResName()))
//                .collect(Collectors.toList());
//        return JSONResult.success(moduleInfos);
//    }

    /**
     * url: /corpApi/organization/permission/getPermissionList
     * http://10.5.119.87:9526/project/494/interface/api/12012
     */
    @PostMapping("/getPermissionList")
    public JSONResult<List<UserMenuTo>> getPermissionTree(@RequestBody CorpId corpId, BaseUserInfo bui) {
        if (BooleanUtils.isFalse(bui.getBgUser())) {
	        if (StringUtils.isBlank(BaseUtils.acquireOrgId(bui))) {
		        throw new CorpBusinessException(OrganizationResponseCodeEnum.GET_ORG_ID_NULL);
	        }
            return JSONResult.success(userSrv.getPermissions(bui.getUid(), bui.getOrgId(), false));
        } else {
            return JSONResult.success(userSrv.getPermissions(null, null, StringUtils.isBlank(corpId.getCorpId())));
        }
    }

    /**
     * url: /corpApi/organization/permission/getPermissionList
     * http://10.5.119.87:9526/project/494/interface/api/12012
     */
    @PostMapping("/newGetPermissionTree")
    public JSONResult<FindPermissionVO> newGetPermissionTree(@RequestBody CorpId corpId, BaseUserInfo bui) {
        List<UserMenuTo> menuTos = new ArrayList<>();
        if (BooleanUtils.isFalse(bui.getBgUser())) {
            if (StringUtils.isBlank(BaseUtils.acquireOrgId(bui))) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.GET_ORG_ID_NULL);
            }
        }
        menuTos = userSrv.getPermissionByUserType();
        List<UserMenuTo> dataPermission = userSrv.findDataPermission();

        return JSONResult.success(new FindPermissionVO(menuTos, dataPermission));
    }

    @Data
    public static class CorpId {
        private String corpId;
    }

    @PostMapping("/generateToken")
    public JSONResult<String> generateToken(BaseUserInfo bui, String source, String token) {
	    if (StringUtils.isBlank(token)) {
		    token = UUID.randomUUID().toString();
	    }
        iCacheHandler.setValue(String.format("%s:%s", source, token), bui);
        return JSONResult.success(token);
    }

    @Data
    public static class ExecResult {
        String std;
        String err;
        int exitVal;
    }

    /**
     * 检查是否越权
     *
     * @param req
     * @return
     */
    @PostMapping("/checkBeyondAuthority")
    public JSONResult<Boolean> checkBeyondAuthority(@RequestBody CheckBeyondAuthorityRequest req) {
        if (req == null) {
            return JSONResult.success(true);
        }
        return JSONResult.success(permissionService.checkBeyondAuthority(req.getUserInfo(), req.getData(), req.getUrl(), req.getSource()));
    }

    /**
     * 清楚越权缓存
     *
     * @return
     */
    @PostMapping("/clearBeyondAuthorityCache")
    public JSONResult<Boolean> clearBeyondAuthorityCache() {
        return JSONResult.success(permissionService.clearBeyondAuthorityCache());
    }
}
